package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.domain.User;
import com.autotest.nore.domain.UserRole;
import com.autotest.nore.dto.RoleDTO;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/autotest/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<RoleDTO>> getRoleList(@PathVariable int goPage, @PathVariable int pageSize,
                                               @RequestBody QueryRequest queryRequest, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        queryRequest.setRequestUser(userName);   // 设置查询人
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, roleService.getRoleList(queryRequest));
    }

    @PostMapping("/user/list/{goPage}/{pageSize}")
    public Pager<List<User>> getRoleUserList(@PathVariable int goPage, @PathVariable int pageSize,
                                             @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, roleService.getRoleUserList(request));
    }

    @PostMapping("/user/delete")
    public void deleteRoleUser(@RequestBody UserRole userRole){
        roleService.deleteRoleUser(userRole);
    }

}
